// Created by wangliang on 2025/6/19.

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_app_demo/base/base_view_model.dart';
import 'package:flutter_app_demo/extension/common.dart';
import 'package:flutter_app_demo/helper/account_helper.dart';
import 'package:flutter_app_demo/mixin/loading_mixin.dart';
import 'package:flutter_app_demo/model/account.dart';
import 'package:flutter_app_demo/net/api_exception.dart';
import 'package:flutter_app_demo/net/common_api.dart';
import 'package:flutter_app_demo/utils/logger.dart';
import 'package:flutter_app_demo/utils/toast.dart';
import 'package:go_router/go_router.dart';

class LoginPageViewModel extends BaseViewModel with LoadingMixin {
  static const maxRemainingSeconds = 60;

  final TextEditingController _phoneEditController = TextEditingController();

  TextEditingController get phoneEditController => _phoneEditController;

  final TextEditingController _codeEditController = TextEditingController();

  TextEditingController get codeEditController => _codeEditController;

  Timer? _timer;
  int _remainingSeconds = maxRemainingSeconds;
  String _remainingSecondsStr = "获取验证码";

  String get remainingSecondsStr => _remainingSecondsStr;
  bool _getCaptchaBtnDisable = false;

  bool get getCaptchaBtnDisable => _getCaptchaBtnDisable;

  void getCaptcha() async {
    var phoneText = _phoneEditController.text;
    if (phoneText.isEmpty) {
      ToastUtil.showToast(context, '请输入手机号');
      return;
    }
    if (!phoneText.isValidPhoneNumber()) {
      ToastUtil.showToast(context, '请输入正确的手机号');
      return;
    }

    showLoading();
    try {
      // TODO 请求验证码
      await Future.delayed(const Duration(seconds: 2));
      hideLoading();
      showToast('验证码发送成功');
      startCountDown();
    } on ApiException catch (exception) {
      hideLoading();
      ToastUtil.showToast(context, exception.message);
    }
  }

  void startCountDown() {
    _timer?.cancel();
    _remainingSeconds = maxRemainingSeconds;
    _getCaptchaBtnDisable = true;
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_remainingSeconds > 0) {
        _remainingSeconds--;
        _remainingSecondsStr = "${_remainingSeconds}S";
        safeBuildView();
      } else {
        _getCaptchaBtnDisable = false;
        _remainingSecondsStr = "获取验证码";
        safeBuildView();
        _timer?.cancel();
      }
    });
  }

  String _vcode = '';
  void onCodeChanged(String value) {
    if ((value.length - _vcode.length).abs() <= 1) {
      _vcode = value;
      safeBuildView();
      return;
    }
    if ('$_vcode$_vcode' == value) {
      //键入重复的情况
      _codeEditController.value = TextEditingValue(
        text: _vcode, //不赋值新的 用旧的;
        selection: TextSelection.fromPosition(
          TextPosition(affinity: TextAffinity.downstream, offset: _vcode.length),
        ), //  此处是将光标移动到最后,
      );
      safeBuildView();
    } else {
      //第一次输入验证码
      _codeEditController.value = TextEditingValue(
        text: value,
        selection: TextSelection.fromPosition(
          TextPosition(affinity: TextAffinity.downstream, offset: value.length),
        ), //  此处是将光标移动到最后,
      );
      _vcode = value;
      safeBuildView();
    }
  }

  Future doLogin() async {
    if (_phoneEditController.text.isEmpty) {
      ToastUtil.showToast(context, '请输入手机号');
      return false;
    }
    if (!_phoneEditController.text.isValidPhoneNumber()) {
      ToastUtil.showToast(context, '请输入正确的手机号');
    }
    if (_codeEditController.text.isEmpty) {
      ToastUtil.showToast(context, '请输入验证码');
      return false;
    }

    showLoading();
    String code = _codeEditController.text;
    String phone = _phoneEditController.text;
    try {
      Account? resp = await CommonApi.userLogin(phone, code);
      if (resp != null) {
        hideLoading();
        await AccountHelper.instance.saveAccount(resp);
        launchHomePage();
      } else {
        hideLoading();
        showToast('登录失败');
      }
    } on ApiException catch (e) {
      Log.e("userLogin error code: $e");
      hideLoading();
      ToastUtil.showToast(context, e.message);
    }
  }

  launchHomePage() => context.push('/home');

  @override
  void dispose() {
    _timer?.cancel();
    _timer = null;
    super.dispose();
  }
}
